package com.lzn.dds.controller;

import com.lzn.dds.common.RestfulResponse;
import com.lzn.dds.dataSource.DBIdentifier;
import com.lzn.dds.dataSource.DynamicDataSource;
import com.lzn.dds.entity.DbSource;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;

/**
 * @author lzn
 * @date 6/10/21 9:05 PM
 */
@RestController
@RequestMapping(value = "/dbsource")
public class SourceController {
    // 根据关键字查询数据源配置信息
    @GetMapping(value = "queryDbByTaskId")
    public DbSource queryDbByTaskId(@RequestParam(value = "ddsId")String ddsId){
        return dbSourceMapper.selectByPrimaryKey(ddsId);
    }
    // 查询接口
    // 写入数据源接口
    // 修改数据源接口
    // 测试是否连接
    public RestfulResponse<Boolean> isConnect(@RequestBody DbSource dbSource){
        try{
            String ddsType = dbSource.getDdsType();
            DBIdentifier.setProjectCode(dbSource.getDdsId());
            Connection connection = DynamicDataSource.instance().getConnection(dbSource);
            if(connection == null){
                // logger "数据库连接测试失败，请检查配置是否正确"
                return new RestfulResponse<>("-100","数据库连接测试失败，请检查配置是否正确",true);
            }
            dbSource.setConnectStatus("Y");
            dbSourceMapper.updateDbSourceInfo(dbSource);
            return new RestfulResponse<>("0","连接成功",true);
        }catch (Exception e){
            return new RestfulResponse<>("-100",e.getMessage(),false);
        }
    }
    // 改变数据源有效状态
    public RestfulResponse<String> isValid(@RequestBody DbSource dbSource){
        try{
            DbSource oldDb = mapper.select(dbSource.getDdsId());
            if(oldDb.getIsvalid().equals(dbSource.getIsvalid())){
                return new RestfulResponse<>("状态没有改变，请重新刷新界面，再次发起请求");
            }
            dbSource.setIsvalid(!oldDb.getIsvalid());
            dbSourceMapper.updateDbSourceInfo(dbSource);
            return new RestfulResponse<>("0","数据库状态修改成功");
        }catch (Exception e){
            return new RestfulResponse<>("-100","修改失败，原因："+e.getMessage(),null);
        }
    }
}
